package org.groovyflow.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import org.codehaus.jackson.*


//TODO  Probably end up using more Jackson JSON, and getting rid of simple org.json.
public class JsonUtil {

	public static JSONArray toJson(List<Map> maps){
		JSONArray arr = new JSONArray();
		for(Map map : maps){
			JSONObject obj = new JSONObject(map);
			arr.put(obj);
		}
		
		return arr;
	}
	
    public static String mapToJson(Map map){
    	JSONObject j = new JSONObject(map);
    	return j.toString();
    } 

	/**Currently only returns a Map that holds Strings as values.  No heirarchical
	*diving either-- just one map returned.  We could get much more 
	*sophisticated if we took time to learn
	*the Jackson JSON parser, which is currently used here just to handle quotes,
	*colons, commas that could appear as user input.
	*/
    public static Object toObject(String str){
		def map = new HashMap()
		
		//According to http://jackson.codehaus.org/0.9.3/javadoc/index.html:
		//JsonFactory is a thread-safe reusable provider of parser and generator instances.
		//That makes one think we should always retrieve the same one from the Spring ApplicationContext.
		//But the same document also says:
		//Creation of a factory instance is quite light-weight operation, 
		//and since there is no need for pluggable alternative implementations 
		//(since there is no "standard" json processor API to implement), 
		//default constructor is used for constructing factories.
		def factory = new JsonFactory()  
		
		StringReader reader = new StringReader(str)
		def parser = factory.createJsonParser(reader)
		
		def work = {
			boolean odd = true
			String key = null
			while(parser.nextToken()){
				String tok = parser.getText()
				//This, among many other things, dooms us not to do heirarichal parsing in this go-round.
				if(tok == "{" || tok == "}"){
					continue;
				}
				if(odd)
					key = tok
				else
					map[key] = tok
				odd = !odd
			}
		}
		//Groovy might close the Reader itself (I don't know)
		//Groovy certainly isn't closing the parser.
		try{
			work()
		}finally{
			try{
				reader.close()
			}finally{
				parser.close()
			}
		}
		
		map
    }


    public static void main(String[] args){
		List<Map> maps = new ArrayList<Map>();
		Map mapOne = new HashMap();
		mapOne.put("key", "value");
		Map mapTwo = new HashMap();
		mapTwo.put("key2", "value2");
		maps.add(mapOne);
		maps.add(mapTwo);
		System.out.println(  toJson(maps).toString());
	}

}
